library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)

survey_long <- readRDS("data/df_long.rds")

survey_long <- survey_long %>% filter(d_affiliated == 1 & d_ownparty == 0)
survey_long <- survey_long %>% 
  group_by(meta_UUID) %>%
  mutate(N_ind = n(), 
         weights = meta_Weight / N_ind,
         weights_manual = manual_weights / N_ind) 

parties <- read.csv("data/cmp_votes.csv") %>% 
  select(evaluated_party, pervote, dem_country_code)

parties_df <- parties[with(parties, order(pervote, decreasing = F)),]

########### Regression analyses

country_abb = c("NL", "PL", "DE", "ES", "SE", "GB", "FR", "IT", "GR")
parties <- survey_long %>% ungroup() %>%  select(evaluated_party, dem_country_code) %>% 
  .[!duplicated(.), ]

models <- list()
country_df <- data.frame()


for(i in 1:length(country_abb)){


  country <- country_abb[i]
  parties_temp <- parties %>% filter(dem_country_code == country)
  party_df <- parties_df %>% filter(dem_country_code == country)
  
  survey_temp <- survey_long %>% filter(dem_country_code == country)
  
  
  survey_temp$evaluated_party <- factor(survey_temp$evaluated_party, 
                                       levels = party_df$evaluated_party[with(party_df, order(pervote, decreasing = T))])
  
  m1 <- feols(close_num ~ feeling_toward*evaluated_party | meta_UUID, survey_temp, 
               weights = survey_temp$weights)
  coef <-m1$coefficients[str_detect(names(m1$coefficients), ":")]
  se <- m1$se[str_detect(names(m1$coefficients), ":")]
  pvalue <- as.character(round(m1$coeftable$`Pr(>|t|)`[str_detect(names(m1$coefficients), ":")], 3))
  names <- names(m1$coefficients)[str_detect(names(m1$coefficients), ":")] %>% 
    str_replace_all(., "feeling_toward:evaluated_party", "")
  
  temp_df <- data.frame(coef = coef,
                        se = se, 
                        evaluated_party = names, 
                        pvalue = pvalue) %>% 
    mutate(pvalue = ifelse(pvalue == "0", "0.000", pvalue), 
           pvalue = ifelse(!is.na(pvalue), paste0("(", pvalue, ")"), pvalue))
  
  temp_df <- parties_temp %>% left_join(temp_df)
  
  country_df <- rbind.data.frame(country_df, temp_df) %>% 
    mutate(coef = ifelse(is.na(coef), 0, coef), 
           se = ifelse(is.na(se), 0, se))
  
  print(i)
}


country_df$evaluated_party <- factor(country_df$evaluated_party, 
                                     levels = country_df$evaluated_party[with(country_df, 
                                                                              order(dem_country_code, coef))])

pd <- position_dodge(0.5)

ggplot(country_df, aes(x = evaluated_party, ymin = coef - se*1.96, y = coef, ymax = coef + se*1.96)) + 
  geom_point(position = pd, shape = 21, fill = 'white') + 
  geom_errorbar(width = 0, position = pd) + 
  xlab("") + 
  ylab("Feeling coefficient X Party Dummy") + 
  coord_flip() + 
  geom_hline(yintercept = 0, linetype="dashed", 
             color = "red", size=.4) + 
  geom_text(aes(label = pvalue), nudge_y = 0.085, inherit.aes = T, size = 3.5) +
  facet_grid(rows = vars(dem_country_code), scales = "free_y") + 
  theme_bw() +
  theme(text = element_text(size = 14)) 

ggsave("figures/FigureA4.jpeg", 
       height = 12, width = 8, dpi = 600)
